package com.lonwin.inspectionmanagement.mvp.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lonwin.inspectionmanagement.R;
import com.lonwin.inspectionmanagement.R2;
import com.lonwin.inspectionmanagement.app.utils.AppUtil;
import com.lonwin.inspectionmanagement.app.utils.TimeUtils;
import com.lonwin.inspectionmanagement.di.component.DaggerSortOutRecordComponent;
import com.lonwin.inspectionmanagement.mvp.contract.SortOutRecordContract;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.SortOutBean;
import com.lonwin.inspectionmanagement.mvp.presenter.SortOutRecordPresenter;
import com.lonwin.inspectionmanagement.mvp.ui.activity.CruiseSearchActivity;
import com.lonwin.inspectionmanagement.mvp.ui.adapter.SortOutRecordAdapter;
import com.lonwin.inspectionmanagement.widget.dialog.LoadingDailog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/15/2018 13:57
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class SortOutRecordFragment extends BaseFragment<SortOutRecordPresenter> implements SortOutRecordContract.View, OnDateSetListener {

    @BindView(R2.id.sortout_record_select_lay)
    LinearLayout sortoutRecordSelectLay;
    @BindView(R2.id.sortout_record_RecyclerView)
    RecyclerView sortoutRecordRecyclerView;

    @BindView(R2.id.sortout_record_startTime)
    TextView sortout_record_startTime;
    @BindView(R2.id.sortout_record_endTime)
    TextView sortout_record_endTime;
    @BindView(R2.id.commonaddress_refresh_layout)
    SmartRefreshLayout commonaddressRefreshLayout;
    Unbinder unbinder;
    private SortOutRecordAdapter sortOutRecordAdapter;
    private boolean isRefersh = false;
    int allpages = 0;
    int pageIndex = 1;
    private TimePickerDialog mDialogAll;
    private LoadingDailog loadingDailog;

    public static SortOutRecordFragment newInstance() {
        SortOutRecordFragment fragment = new SortOutRecordFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerSortOutRecordComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sort_out_record, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadingDailog = new LoadingDailog.Builder(getActivity()).setMessage("处理中...").create();
        sortout_record_startTime.setText(TimeUtils.getFirstDayAndFirstMonth());
        sortout_record_endTime.setText(TimeUtils.getNowDayAndMonth());
        initTime();
        sortoutRecordRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        sortOutRecordAdapter = new SortOutRecordAdapter(new ArrayList<>());
        sortOutRecordAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        sortoutRecordRecyclerView.setAdapter(sortOutRecordAdapter);

        sortoutRecordSelectLay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CruiseSearchActivity.class);
                intent.putExtra("type", "SortOutRecord");
                startActivityForResult(intent, 1001);
            }
        });
        commonaddressRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefersh = true;
                allpages = 0;
                pageIndex = 1;
                commonaddressRefreshLayout.finishRefresh(1500);
                mPresenter.getDigestedXcjlIndex(sortout_record_startTime.getText().toString(), sortout_record_endTime.getText().toString(), pageIndex, "");
//                mPresenter.getUndigestedXcjl(sortout_record_startTime.getText().toString(),sortout_record_endTime.getText().toString(),pageIndex);
            }
        });
        commonaddressRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefersh = false;
                if (allpages == pageIndex || allpages < pageIndex) {
                    ArmsUtils.makeText(getActivity(), "已经全部加载");
                    commonaddressRefreshLayout.finishLoadMore();
                    return;
                }
                pageIndex++;
                commonaddressRefreshLayout.finishLoadMore(1000);
                mPresenter.getDigestedXcjlIndex(sortout_record_startTime.getText().toString(), sortout_record_endTime.getText().toString(), pageIndex, "");

            }
        });
        sortout_record_startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogAll.show(getFragmentManager(), "开始时间");

            }
        });
        sortout_record_endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mDialogAll.show(getFragmentManager(), "结束时间");
            }
        });
    }

    public void initTime() {
        mDialogAll = new TimePickerDialog.Builder()
                .setCallBack(SortOutRecordFragment.this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择查询时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
//                         .setHourText("Hour")
//                         .setMinuteText("Minute")
                .setCyclic(false)
//            .setMinMillseconds(System.currentTimeMillis()-(100*365*24*60*60*1000))
//                         .setMaxMillseconds(System.currentTimeMillis()+10*1000 )
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.color_FF098DDB))
                .setType(Type.YEAR_MONTH_DAY)
//                         .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
//                         .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(14)
                .build();
    }

    @Override
    public void onResume() {
        super.onResume();
        commonaddressRefreshLayout.autoRefresh();
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        loadingDailog.show();
    }

    @Override
    public void hideLoading() {
        loadingDailog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getActivity(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public Activity getMyActivity() {
        return getActivity();
    }

    @Override
    public void getDigestedXcjlIndexSuccess(SortOutBean.DataBean dataBeans) {
//           if (recordsBeans==null||recordsBeans.isEmpty())
//           {    sortOutRecordAdapter.setNewData(recordsBeans);
//               sortOutRecordAdapter.setEmptyView(ArmsUtils.inflate(getActivity(),R.layout.empty_view));
//               return;
//           }
//           sortOutRecordAdapter.setNewData(recordsBeans);

        if (dataBeans == null || dataBeans.getTotal() < 1) {
            if (isRefersh) {
                sortOutRecordAdapter.setNewData(null);
            }
            sortOutRecordAdapter.setEmptyView(ArmsUtils.inflate(getActivity(), R.layout.empty_view));
            return;
        }
        this.allpages = dataBeans.getPages();
        if (isRefersh) {
            //没有数据,需要处理
            sortOutRecordAdapter.setNewData(dataBeans.getRecords());
            commonaddressRefreshLayout.finishRefresh();
        } else {
            sortOutRecordAdapter.addData(dataBeans.getRecords());
            commonaddressRefreshLayout.finishLoadMore(500);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        timePickerView.dismiss();
        if (timePickerView.getTag().equals("开始时间")) {
            sortout_record_startTime.setText(TimeUtils.longToStrTime(millseconds));

        } else {
            sortout_record_endTime.setText(TimeUtils.longToStrTime(millseconds));
        }
        if (sortout_record_startTime.getText().toString().compareTo(sortout_record_endTime.getText().toString()) < 0) {
            commonaddressRefreshLayout.autoRefresh();
            return;
        }
        showMessage("开始时间不能大于结束时间");
    }
}
